<template>
    <i style="z-index: 99999;">
        <div class="VideoAssembly">
            <i @click="onCloseVideo($event)" class="iconfont iconguanbi"></i>
            <div class="frame">
                <v-liveplayer1 style="box-sizing: border-box;width: 100%; height: 100%;" :videoIndex="GWVideoValue[3]"></v-liveplayer1>
                <div class="no-login"></div>
            </div>
        </div>
    </i>
</template>

<script>
/* eslint-disable */
import $ from 'jquery';
import './videoPlaybackCom/adapter.js';
import './videoPlaybackCom/platform.js';
import { H5sPlayerWS, H5sPlayerHls, H5sPlayerRTC } from './videoPlaybackCom/h5splayer.js';
import { H5siOS, H5sPlayerCreate, H5sSafariBrowser, GetURLParameter } from './videoPlaybackCom/h5splayerhelper.js';
import Vue from 'vue';
import Liveplayer1 from './videoPlaybackCom/videoPlayerComponent.vue';
export default {
    name: 'GWVideo',
    props: ['GWVideoValue'],
    components: {
        'v-liveplayer1': Liveplayer1
    },
    data () {
        return {
            // 回放总时间与进行时间
            backTotal: '00:00:00',
            currentTime: '00:00:00',
            // 当前通道是否被选中
            roadTag: false,
            // 视频要被减去的高度
            videoPerHeight: 32,
            screenWidth: 0,
            setZoom: 0,
            backEqName: '',
            picModal: false,
            url: this.$store.state.serverUrl,
            realData: '',
            selectCol: 1,
            n: 1,
            selectRow: 1,
            contentHeight: '',
            cProto: 'RTC',
            clickVideoId: 'h11',
            clickH5VideoId: 'hvideo11',
            downLoad: false,
            backVideo: undefined,
            region: 1, // 倍速
            displayc: '', // 实时时间
            rowstarf: '', // 跟进进度条开始时间
            rowend: '', // 进度条结束时间
            timelink: 0, // 滑块
            max: 0, // 滑块最大值
            icon: 'iconfont icon_bofang', // 暂停图片
            activeName: 'first',
            searchTime: [new Date(new Date(new Date().toLocaleDateString()).getTime()), new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)],
            searchType: 'record',
            cToken: '',
            docData: [],
            options: [
                {
                    value: 'snapshot',
                    label: '查看快照'
                },
                {
                    value: 'record',
                    label: '查看回放'
                }
            ],
            // 分支列表数据
            onlineData: [
                {
                    label: '中心',
                    children: []
                }
            ],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            defaultProps2: {
                children: 'children',
                label: 'label'
            },
            loadingEquipList: true,
            showVideo: false,

            videoIndex: 1,
        };
    },
    // 创建完毕
    created () {

    },

    mounted () {
        console.log('将要播放的视频通道---', this.GWVideoValue)
        this.playVideo1()
        // 获取所有视频配置
        //this.getVideoConfigs1();
        // ID: 4
        // EquipNum: 100
        // ChannelName: "通道4"
        // StreamType: 0
        // Path: "中心%公司海康NVR37-公司前台"
        // token: "site1-2c27--37"
        // console.log(this.realData);

        // console.log(this.clickH5VideoId);  //hvideo11
        // console.log(this.cProto); //RCT
        // console.log(this.clickVideoId+"============="); // h11

    },
    beforeRouteLeave (to, from, next) {
        try {
            this.$store.state.usingEq = [];
        } catch (e) {
            console.log(e)
        }
        next();
    },
    methods: {
        // 关闭视频
        onCloseVideo () {
            this.$root.bus.$emit('closeAllVideo1');
        },
        //播放视频
        playVideo1 (e) {
            this.showVideo = !this.showVideo;
            if (this.showVideo) {
                var realData = {
                    ID: 4,
                    EquipNum: this.GWVideoValue[0],
                    ChannelName: "通道4",
                    StreamType: 0,
                    Path: this.GWVideoValue[1],
                    token: this.GWVideoValue[2],
                };
                this.$root.bus.$emit('videoPlay1', realData, 'video' + this.GWVideoValue[3], 'RTC', 'main', 'h1'); // 这里视频播放默认为主码流
            }
            else {
                $(".video-floor-main-img").find("i").css("z-index", 1);
                this.$root.bus.$emit('closeAllVideo1', 2); //先关闭所有通道
            }

        },
        // 关闭所有视频
        closeAllVideo () {
            this.$store.state.usingEq = [];
            this.$root.bus.$emit('closeAllVideo1');
        },
        // 下载回放与快照
        downData1 (add, e) {
            e.stopPropagation();
            this.$notify.info({
                title: '',
                message: '正在下载资源，请稍后'
            });
            this.downLoad = true;
            let downUrl = this.$store.state.serverUrl + add;

            this.$api
                .getVideoDownResource({
                    url: downUrl
                })
                .then(res => {
                    let code = res.data.HttpStatus;
                    if (code === 200) {
                        this.downLoad = false;
                        this.$notify({
                            title: '',
                            message: '已保存至本地: D:/Alarmcenter/data',
                            type: 'success'
                        });
                    }
                });
        },

        // 播放速度调整
        speedChange1 (type) {
            if (this.backVideo === undefined) {
                this.$Notice.info({
                    title: '请选择视频'
                });
                return;
            }
            if (type === 'slower') {
                if (this.region === 0.5) {
                    return;
                }
                this.region = this.region / 2;
            } else {
                if (this.region === 16) {
                    return;
                }
                this.region = this.region * 2;
            }
            this.backVideo.speed(this.region);
        },

        // 视频播放器
        // 开始
        resume1 () {
            if (this.backVideo === undefined) {
                this.$Notice.info({
                    title: '请选择视频'
                });
                return;
            }

            var strart = this.icon;
            if (strart == 'iconfont icon_zanting1') {
                this.icon = 'iconfont icon_bofang';
                this.backVideo.pause();
            }
            if (strart == 'iconfont icon_bofang') {
                this.icon = 'iconfont icon_zanting1';
                this.backVideo.resume1();
            }
        },
        timelinn1 (timelink) {
            this.backVideo.seek(timelink);
        },

        // 倍速
        Speed1 () {
            if (this.backVideo === undefined) {
                this.$Notice.info({
                    title: '请选择视频'
                });
                return;
            }
            this.backVideo.speed(this.region);
        },

        // 关闭
        Close1 () {
            if (this.backVideo != undefined) {
                this.backVideo.disconnect();
                delete this.backVideo;
                this.backVideo = undefined;
            }
        },

        PlaybackCB1 (event, userdata) {
            var msgevent = JSON.parse(event);
            if (msgevent.type === 'H5S_EVENT_PB_TIME') {
                console.log('line', msgevent);

                let interval = this.getSecond1(this.rowstarf, msgevent.pbTime.strTime);
                this.currentTime = this.getFormatTime1(interval);

                this.displayc = msgevent.pbTime.strTime;
                var starf = new Date(this.rowstarf).getTime() / 1000;
                var endd = new Date(msgevent.pbTime.strTime).getTime() / 1000;
                var staefend = endd - starf;
                this.timelink = staefend;
            }
        },

        // 返回开始时间与结束时间相差秒数
        getSecond1 (Stime, Etime) {
            var stimeSecond = new Date(Stime),
                etimeSecond = new Date(Etime);
            var leave = etimeSecond.getTime() - stimeSecond.getTime();
            return parseInt(leave) / 1000;
        },

        // 修改秒数的时间格式
        getFormatTime1 (seconds) {
            var parseTime = seconds;
            //seconde
            if (parseTime < 60) parseTime = '00:00:' + (parseTime < 10 ? '0' + parseTime : parseTime);
            //minute
            else if (parseTime >= 60 && parseTime < 3600) {
                var minute = parseTime / 60 + '';
                if (minute.indexOf('.') != -1) {
                    minute = minute.substr(0, minute.indexOf('.'));
                }
                var second = parseTime - 60 * parseInt(minute);
                parseTime = '00:' + (minute < 10 ? '0' + minute : minute) + ':';
                parseTime += second < 10 ? '0' + second : second;
            }
            //hour
            else if (parseTime >= 3600) {
                var hour = parseTime / 3600 + '';
                if (hour.indexOf('.') != -1) {
                    hour = hour.substr(0, hour.indexOf('.'));
                }
                var minute = parseTime - 3600 * parseInt(hour);
                minute = (parseTime - 3600 * parseInt(hour)) / 60 + '';
                if (minute.indexOf('.') != -1) {
                    minute = minute.substr(0, minute.indexOf('.'));
                }
                var second = parseTime - 3600 * parseInt(hour) - 60 * parseInt(minute);
                parseTime = (hour < 10 ? '0' + hour : hour) + ':';
                parseTime += (minute < 10 ? '0' + minute : minute) + ':';
                parseTime += second < 10 ? '0' + second : second;
            }
            return parseTime;
        },

        checkInfo1 (row) {
            let dat = row.data;
            let path = dat.strPath;
            let interSec = this.getSecond1(dat.strStartTime, dat.strEndTime);
            this.backTotal = this.getFormatTime1(interSec);
            let judge = path.substring(path.length - 3, path.length);
            if (judge !== 'jpg') {
                this.icon = 'iconfont icon_zanting1';
                if (this.backVideo !== undefined) {
                    this.backVideo.disconnect();
                    delete this.backVideo;
                    this.backVideo = undefined;
                    console.log('已断开连接');
                }
                this.rowstarf = dat.strStartTime;
                this.rowend = dat.strEndTime;
                var pbconf1 = {
                    begintime: dat.strStartTime,
                    endtime: dat.strEndTime,
                    showposter: 'true', // 'true' or 'false' show poster
                    callback: this.PlaybackCB1,
                    serverpb: 'true',
                    userdata: this // user data
                };
                let conf = {
                    videoid: 'back',
                    protocol: this.$store.state.realProtocol, // http: or https:
                    host: this.$store.state.realHost, // localhost:8080
                    rootpath: '/', // '/'
                    token: dat.strToken,
                    pbconf: pbconf1, // This is optional, if no pbconf, this will be live.
                    hlsver: 'v1', // v1 is for ts, v2 is for fmp4
                    session: window.localStorage.ac_session
                };

                var end = new Date(dat.strEndTime).getTime();
                var starf = new Date(dat.strStartTime).getTime();
                var starfend = (end - starf) / 1000; // 时间差
                this.max = starfend;
                this.backVideo = new H5sPlayerRTC(conf);
                this.backVideo.connect();
                setTimeout(
                    function () {
                        this.backVideo.start();
                    }.bind(this),
                    500
                );
            } else {
                this.picModal = true;
                this.url = this.$store.state.serverUrl;
                this.url += path;
            }
        },

        // 视频区域全屏显示
        FullScreen1 () {
            let aimDom = '#backVideo';
            let elem = '';
            elem = $(aimDom).get(0);
            if (document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled) {
                if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.webkitExitFullscreen) {
                        document.webkitExitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    this.updateUIExitFullScreen1();
                } else {
                    console.log('panelFullScreen3');
                    // $('#videoPanel').height(1080);
                    if (elem.requestFullscreen) {
                        elem.requestFullscreen();
                    } else if (elem.webkitRequestFullscreen) {
                        elem.webkitRequestFullscreen();
                    } else if (elem.mozRequestFullScreen) {
                        elem.mozRequestFullScreen();
                    } else if (elem.msRequestFullscreen) {
                        elem.msRequestFullscreen();
                    }
                }
            } else {
                console.log('Fullscreen is not supported on your browser.');
            }
        },

        // 进入全屏后调整样式
        updateUIEnterFullScreen1 () {
            $('div[name="flex"]').height(screen.height / this.rows);
        },

        // 退出全屏后调整样式
        updateUIExitFullScreen1 () {
            if (!document.fullscreenElement && !document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) {
                $('div[name="flex"]').height(this.contentHeight / this.rows);
            }
        },

        // 面板全部通道全屏
        panelFullScreen1 (event) {
            var elem = document.getElementById('videoPanel');
            // var elem = $("#videoPanel");
            console.log('panelFullScreen', event);
            if (document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled) {
                if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.webkitExitFullscreen) {
                        document.webkitExitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    this.updateUIExitFullScreen1();
                } else {
                    console.log('panelFullScreen3');

                    if (elem.requestFullscreen) {
                        elem.requestFullscreen();
                    } else if (elem.webkitRequestFullscreen) {
                        elem.webkitRequestFullscreen();
                    } else if (elem.mozRequestFullScreen) {
                        elem.mozRequestFullScreen();
                    } else if (elem.msRequestFullscreen) {
                        elem.msRequestFullscreen();
                    }
                    this.updateUIEnterFullScreen1();
                    if (document.addEventListener) {
                        document.addEventListener('webkitfullscreenchange', this.updateUIExitFullScreen1, false);
                        document.addEventListener('mozfullscreenchange', this.updateUIExitFullScreen1, false);
                        document.addEventListener('fullscreenchange', this.updateUIExitFullScreen1, false);
                        document.addEventListener('MSFullscreenChange', this.updateUIExitFullScreen1, false);
                    }
                }
            } else {
                console.log('Fullscreen is not supported on your browser.');
            }
        },

        // 更新UI高度
        updateUI1 () {
            if ($(document.body).width() < 768) {
                this.contentHeight = $(document.body).height() * 0.4;
            } else {
                this.contentHeight = $(document.body).height() * 0.8 - this.videoPerHeight;
            }
            $('div[name="flex"]').height(this.contentHeight / this.rows);
            let that = this;
            if (H5siOS() === true) {
                $('.h5video').prop('controls', true);
            }
        },

        // 改变页面通道数
        changePanel1 (event) {
            let data = $(event.target).data('row');
            data = data.split('|');
            let cols = data[1];
            let rows = data[0];
            let that = this;
            Object.assign(this.$data, {
                rows: parseInt(rows),
                cols: parseInt(cols)
            });
            Vue.nextTick(function () {
                $('div[name="flex"]').height(that.contentHeight / rows);
            });

            if (this.screenWidth <= 1280) {
                switch (cols) {
                    case '1':
                        this.setZoom = 0;
                        break;
                    case '2':
                        this.setZoom = 0.72;
                        break;
                    case '3':
                        this.setZoom = 0.5;
                        break;
                    case '4':
                        this.setZoom = 0.44;
                        break;
                }
            } else {
                switch (cols) {
                    case '1':
                        this.setZoom = 1.4;
                        break;
                    case '2':
                        this.setZoom = 1;
                        break;
                    case '3':
                        this.setZoom = 0.68;
                        break;
                    case '4':
                        this.setZoom = 0.5;
                        break;
                }
            }
            this.$root.bus.$emit('changeZoom', this.setZoom);
        },

        // 设定指定行列并修改样式
        videoClick1 (r, c, $event) {
            let aimDom = $($event.target).parents('.frame');
            this.clickVideoId = 'h' + r + c;
            this.clickH5VideoId = 'hvideo' + r + c;
            this.selectCol = c;
            this.selectRow = r;
            if (!aimDom.hasClass('videoClickLight')) {
                $('#videoPanel div[class*="videoClickLight"]').removeClass('videoClickLight');
                aimDom.addClass('videoClickLight');
                this.roadTag = true;
            } else {
                $('#videoPanel div[class*="videoClickLight"]').removeClass('videoClickLight');
                let next = this.autoPlayNext1(this.clickH5VideoId);
                if (next === undefined) {
                    this.clickH5VideoId = 'hvideo11';
                    this.clickVideoId = 'h11';
                    return;
                }
                this.clickH5VideoId = 'hvideo' + next;
                this.clickVideoId = 'h' + next;
                this.roadTag = false;
            }
        },

        // 整理树分支数据
        sortTreeDat1 (dat) {
            let obj = {};
            let target = {};
            let option = [];
            for (let i = 0; i < dat.length; i++) {
                obj = {};
                target = dat[i];
                obj.label = target.Path.substring(3);
                obj.realData = target;
                option.push(obj);
            }
            this.onlineData[0].children = option;
        },

        // 切换视频
        changeVideo1 (data) {
            let next = '';
            this.realData = data.realData;
            if (data.children) {
                return;
            }
            let choosedTitle = this.realData.Path;
            let titleName = choosedTitle.split('%')[0] + ' - ' + choosedTitle.split('%')[1];
            if (!this.addUsingEq1(titleName)) {
                this.$Notice.info({
                    title: '通道已存在该设备视频！'
                });
                return;
            }

            this.$root.bus.$emit('videoPlay', this.realData, this.clickH5VideoId, this.cProto, 'main', this.clickVideoId); // 这里视频播放默认为主码流

            // 在没选中指定窗口的情况下，自动接下一个窗口播放视频
            if (!this.roadTag) {
                next = this.autoPlayNext1(this.clickH5VideoId);
                if (next === undefined) {
                    this.clickH5VideoId = 'hvideo11';
                    this.clickVideoId = 'h11';
                    return;
                }
                this.clickH5VideoId = 'hvideo' + next;
                this.clickVideoId = 'h' + next;
            }
        },

        // 自动选择下一个播放框
        autoPlayNext1 (id) {
            let num = id.slice(-2);
            let numSet = num.split('');
            let result = '';
            for (let i in numSet) {
                numSet[i] = parseInt(numSet[i]);
            }
            if (numSet[1] < this.rows) {
                numSet[1] += 1;
                result = numSet[0] + '' + numSet[1];
                return result;
            } else if (numSet[0] < this.rows) {
                numSet[0] += 1;
                numSet[1] = 1;
                result = numSet[0] + '' + numSet[1];
                return result;
            }
        },

        // 记录正在使用的监控视频
        addUsingEq1 (eqName) {
            let set = this.$store.state.usingEq;

            for (let i = 0; i < set.length; i++) {
                if (set[i] === eqName) {
                    return false;
                }
            }
            set.push(eqName);
            this.$store.state.usingEq = set;
            return true;
        },

        // 选择监控设备
        chooseEq1 (data) {
            let eqName = data.realData.Path;
            eqName = eqName.split('%');
            this.backEqName = eqName[0] + ' - ' + eqName[1];

            if (data.children) {
                return;
            }
            this.cToken = data.realData.token;
        },


        // 时间格式转换 0
        timeFormat1 (val) {
            let arr = val.split('T');
            let dateResult = '';
            let timeResult = '';
            let date = arr[0];
            let time = arr[1];

            date = date.split('-');
            dateResult = date[0] + '年' + date[1] + '月' + date[2] + '日';
            timeResult = time.substring(0, 8);
            return dateResult + ' ' + timeResult;
        },



        // 获取所有视频配置
        getVideoConfigs1 () {
            this.$api
                .getVideoConfig({})
                .then(res => {
                    console.log(res)
                    var result = res.data;
                    if (result.code == 200 && result.data.length > 0) {
                        var itemEquipNo = -1;
                        for (var i = 0; i < result.data.length; i++) {
                            if (result.data[i].communicationDrv == 'GWLSTECH.NET.dll') {
                                itemEquipNo = result.data[i].equipNo;
                                this.$store.state.realProtocol = result.data[i].reserve1
								if(result.data[i].reserve1 === 'http:') {
								    this.$store.state.realHost = result.data[i].localAddr.split(':')[0] + ':8080'
								}else {
								    this.$store.state.realHost = result.data[i].localAddr.split(':')[0] + ':8443'
								}
                                break;
                            }
                        }
                        if (itemEquipNo != -1) {
                            this.getVideoInfor1(itemEquipNo);
                        }
                    }
                })
                .catch(err => {
                    console.log(' 获取所有视频配置失败！');
                });
        },

        // 判断字符串是否为空
        isNull (str) {
            return str === null || str.length === 0 || str === '';
        },

        // 获取所有视频信息
        getVideoInfor1 (strEquipNo) {
            this.loadingEquipList = true;

            this.$api
                .getVideoAllInfo({
                    equip_no: strEquipNo
                })
                .then(res => {
                    var result = res.data;
                    if (result.code == 200 && result.data.length > 0) {
                        this.loadingEquipList = false;
                        var realDataArr = [];
                        for (var i = 0; i < result.data.length; i++) {
                            realDataArr.push({
                                ID: result.data[i].id,
                                EquipNum: result.data[i].equipNum,
                                ChannelName: result.data[i].channelName,
                                StreamType: result.data[i].channelType,
                                Path: result.data[i].path,
                                token: result.data[i].reserve1
                            });
                        }
                        this.sortTreeDat1(realDataArr);
                    }
                })
                .catch(err => {
                    this.loadingEquipList = false;
                    console.log('获取所有视频信息失败！');
                });
        }
    }
};
</script>

<style lang="scss" src="@assets/styles//VideoSystem.scss" scoped></style>
